using System;
using System.IO;

namespace PerformanceDude.MSBuildProfiler
{
    public delegate void ProgressChangedEventHandler(object sender, ProgressChangedEventArgs args);

    public class ReadProgressStream : ContainerStream
    {
        private int lastProgress = 0;
        public event ProgressChangedEventHandler ProgressChanged;

        public ReadProgressStream(Stream stream) : base(stream)
        {
            if (!stream.CanRead || !stream.CanSeek || stream.Length <= 0)
            {
                throw new ArgumentException("Stream not supported", "stream");
            }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            int amountRead = base.Read(buffer, offset, count);
            if (ProgressChanged != null)
            {
                int newProgress = (int) (Position*100.0/Length);
                if (newProgress > lastProgress)
                {
                    lastProgress = newProgress;
                    ProgressChanged(this, new ProgressChangedEventArgs(lastProgress));
                }
            }
            return amountRead;
        }
    }

    public class ProgressChangedEventArgs : EventArgs
    {
        private int lastProgress;

        public ProgressChangedEventArgs(int lastProgress)
        {
            this.lastProgress = lastProgress;
        }

        public int LastProgress
        {
            get { return lastProgress; }
        }
    }
}